package sky.cin.framework.ioms.registry.center.controller;

import sky.cin.framework.ioms.registry.center.entities.MicroService;
import sky.cin.framework.extension.log.Croog;
import sky.cin.framework.network.dto.HttpServletRequest;
import sky.cin.framework.sfoc.core.annotations.beans.Autowired;
import sky.cin.framework.sfoc.core.annotations.beans.Controller;
import sky.cin.framework.sfoc.core.annotations.https.GetMapping;
import sky.cin.framework.sfoc.core.annotations.https.RequestMapping;
import sky.cin.framework.sfoc.core.annotations.https.RequestParam;
import sky.cin.framework.ioms.common.entities.*;

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

@Controller
@RequestMapping("/registry")
public class RegistryController {
    
    @Autowired
    private Croog logger;

    private Map<String, Map<String, MicroService>> manager = new HashMap<>();

    @GetMapping("/login")
    public boolean login(
            HttpServletRequest request,
            @RequestParam("name") String serviceName,
            @RequestParam("balance") String balance
    ) {
        boolean flag;
        String host = request.getHeader("host");
        if (manager.containsKey(serviceName)) {
            Map<String, MicroService> msMap = manager.get(serviceName);
            if (msMap.containsKey(host)) {
                flag = false;
            } else {
                msMap.put(host, new MicroService(serviceName, host, balance));
                flag = true;
            }
        } else {
            Map<String, MicroService> msMap = new HashMap<>();
            msMap.put(host, new MicroService(serviceName, host, balance));
            manager.put(serviceName, msMap);
            flag = true;
        }
        return flag;
    }

    @GetMapping("/heart")
    public void heart(
            HttpServletRequest request
    ) {
        String host = request.getHeader("host");

        manager.values().stream()
            .filter(msMap -> msMap.containsKey(host))
            .findFirst()
            .ifPresent(msMap -> msMap.get(host).refresh());

    }
    
    @GetMapping("/server-list")
    public Map<String, Map<String, MicroService>> list() {
        return manager;
    }
    
    @GetMapping("/query")
    public ServiceEndPoint query(
            HttpServletRequest request,
            @RequestParam("name") String serviceName
    ) {
        String host = request.getHeader("host");
        MicroService ms = null;
        // 先把断开连接的服务（仅被调用的一方）清掉
        Map<String, MicroService> msMap = manager.get(serviceName);
        Iterator<Map.Entry<String, MicroService>> iterator = msMap.entrySet().iterator();
        while (iterator.hasNext()) {
            Map.Entry<String, MicroService> entry = iterator.next();
            if (entry.getValue().dead()) {
                System.out.println(entry.getValue());
                iterator.remove();
            }
        }
        // 找到当前服务（主动调用的一方）
        ms = manager.values().stream()
            .filter(item -> item.containsKey(host))
            .findFirst()
            .map(item -> item.get(host))
            .orElse(ms);
        return ms.select(serviceName, msMap);
    }

}
